<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>最佳拍档</title>
    <meta name="keywords" content="最佳拍档">
    <meta name="description" content="最佳拍档">
    <style>
        .layui-form-label {
            width: 100px;
        }
        .layui-input-block {
            margin-left: 130px;
        }
    </style>
</head>
<body>
        <!--右侧-->
        <div class="right" style="padding: 20px 20px 0px 20px">
            <fieldset class="layui-elem-field layui-field-title" style="margin-top: 50px;">
                <legend id="title"></legend>
            </fieldset>
            <form class="layui-form" lay-filter="RecordForm" style="padding-bottom: 200px;">
                <div class="layui-form-item" id="openeaId_id">
                    <label class="layui-form-label">平台ID</label>
                    <div class="layui-input-block">
                        <input type="text" name="openeaId" placeholder="暂无" autocomplete="off" class="layui-input" readonly>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">姓名</label>
                    <div class="layui-input-block">
                        <input type="text" name="userName" placeholder="请填姓名" required lay-verify="required" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">手机</label>
                    <div class="layui-input-block">
                        <input type="text" name="phone" placeholder="手机号" required lay-verify="phone" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">学历</label>
                    <div class="layui-input-inline">
                        <select name="education" lay-verify="">
                            <option value="小学">小学</option>
                            <option value="初中">初中</option>
                            <option value="高中">高中</option>
                            <option value="大专">大专</option>
                            <option value="本科">本科</option>
                            <option value="硕士">硕士</option>
                        </select>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">年龄</label>
                    <div class="layui-input-block">
                        <input type="text" name="age" placeholder="请填写年龄" lay-verify="number" autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">销售岗位</label>
                    <div class="layui-input-block">
                        <select name="post" lay-verify="">
                            <option value="上游兼职">上游兼职</option>
                            <option value="上游半职">上游半职</option>
                            <option value="上游全职">上游全职</option>
                            <option value="下游兼职">下游兼职</option>
                            <option value="下游半职">下游半职</option>
                            <option value="下游全职">下游全职</option>
                        </select>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">入职日期</label>
                    <div class="layui-input-block">
                        <input type="text" class="layui-input" name="entryTime" required lay-verify="required" id="entryTimeid" readonly>
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">简历附件</label>
                    <div class="layui-input-block">
                        <div id="attachment_content" style="padding-top: 3px;padding-bottom: 5px;"></div>
                        <input id="fileSelector" type="file">
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button class="layui-btn" id="SubmitBtn" lay-submit lay-filter="submitForm">立即提交</button>
                    </div>
                </div>
            </form>
        </div>
</body>
<script src="https://unpkg.com/cos-js-sdk-v5/dist/cos-js-sdk-v5.min.js"></script>
<script type="text/javascript">
    let cos = new COS({
        SecretId: 'AKIDfATcXDdpmW3LOCl48xWptjKflcDZgYAY',
        SecretKey: 'B6mDOK1TggSzGI4buynMgkY8SXMvFK9j',
    });
    let Bucket = 'dev-1308272144'
    let Region = 'ap-guangzhou'
    let folderName = "cms"
    let attachments = []
    let OriginalData = {}
    let assistantId = ""
    window.onload=function(){
        assistantId = GetQueryString("assistantId")
        if(isNotNull(assistantId)){//编辑
            initFormData(assistantId)
            $("#title").text("修改助理信息")
        }else{//新增
            $("#openeaId_id").hide();
            $("#title").text("添加助理信息")
        }
        //初始化导航栏选中
        $('a[href="/Admin/Sales/AssistantManagement"]').parent().addClass('layui-this');
        $('a[href="/Admin/Sales/AssistantManagement"]').parent().parent().parent().addClass('layui-nav-itemed');
    }

    //初始化表单数据
    function initFormData(assistantId) {
        $.ajax({
            url: '/sales/assistant/'+assistantId,
            type: 'get',
            data: {},
            dataType: 'json', // 用于设置响应体的类型 注意 跟 data 参数没关系！！！
            success: function (res) {
                layui.use('form', function(){
                    OriginalData = res.data
                    var form = layui.form;
                    //给表单赋值
                    form.val("RecordForm", {
                        "openeaId": res.data.openeaId
                        ,"userName": res.data.userName
                        ,"phone": res.data.phone
                        ,"education": res.data.education
                        ,"age": res.data.age
                        ,"post": res.data.post
                        ,"entryTime": res.data.entryTime
                    });
                    //初始化简历附件
                    let attachs = res.data.cvFile;
                    if(isNotNull(attachs)){
                        attachments = attachs.split(",");
                        randerAttachList(0)
                    }
                });
            }
        });
    }

    //表单提交
    layui.use('form', function(){
        var form = layui.form;
        form.on('submit(submitForm)',function (res) {
            OriginalData.userName = $('input[name="userName"]').val()
            OriginalData.phone = $('input[name="phone"]').val()
            OriginalData.education = $('select[name="education"] option:selected').val()
            OriginalData.age = $('input[name="age"]').val()
            OriginalData.post = $('select[name="post"] option:selected').val()
            OriginalData.entryTime = $('input[name="entryTime"]').val()
            //保存简历附件链接
            if(attachments.length > 0){
                let backUrls = "";
                for (let i in attachments){
                    if(backUrls == ""){
                        backUrls = attachments[i];
                    }else{
                        backUrls += "," + attachments[i];
                    }
                }
                OriginalData.cvFile = backUrls;
            }else{
                OriginalData.cvFile = "";
            }
            let type = "POST";
            let url = "/sales/assistant/add"
            if(isNotNull(assistantId)){//编辑
                type = "PUT";
                url = "/sales/assistant/edit";
            }
            $.ajax({
                type:type,
                url:url,
                data:JSON.stringify(OriginalData),
                dataType:'json',
                contentType: 'application/json; charset=UTF-8',
                success:function(req){
                    layui.use('layer', function(){
                        var layer = layui.layer;
                        if(isNotNull(assistantId)){//编辑
                            layer.msg("更新成功！");
                        }else{//新增
                            layer.msg("新增成功！");
                        }
                    });
                    // 两秒后重载表格数据
                    setTimeout(function(){
                        window.location.href = "http://" + window.location.host + "/Admin/Sales/AssistantManagement";
                    }, 2000);
                    return false;
                },
                error:function(e){
                    layui.use('layer', function(){
                        var layer = layui.layer;
                        if(isNotNull(assistantId)){//编辑
                            layer.msg("更新失败！");
                        }else{//新增
                            layer.msg("新增失败！");
                        }
                    });
                }
            })
            return false;
        })
    });

    layui.use('laydate', function(){
        let laydate = layui.laydate;
        laydate.render({
            elem: '#entryTimeid',
            trigger: 'click',
            done: function(value, date, endDate){
                console.log(value); //得到日期生成的值，如：2017-08-18
                console.log(date); //得到日期时间对象：{year: 2017, month: 8, date: 18, hours: 0, minutes: 0, seconds: 0}
                console.log(endDate); //得结束的日期时间对象，开启范围选择（range: true）才会返回。对象成员同上。
            },
            close: function(that){ // 关闭后的回调
                // …
            }
        });
    });

    //简历上传
    $("#fileSelector").change(function () {
        let file = $("#fileSelector")[0].files;
        let url = uploadCOS(file);
        if(isNotNull(url)){
            attachments = [];
            attachments.push(url);//上传完毕添加到attachments中
            randerAttachList(1);//重新渲染附件列表
        }
    });

    //渲染附件列表：0为展示列表，1为可删除列表
    function randerAttachList(flag){
        $("#attachment_content").html("");//先清空附件列表显示
        for(let i in attachments){
            let attach = attachments[i];
            let filename = attach.substring(attach.lastIndexOf("/")+1);
            if(flag == 0){
                $("#attachment_content").append("<p style='color: #1ea0fa;padding-bottom: 3px;' id='attachment_list"+i+"'><a href='"+attach+"' target='_blank'>"+filename+"</a></p>")
            }else if(flag == 1){
                $("#attachment_content").append("<p style='color: #1ea0fa;padding-bottom: 3px;' id='attachment_list"+i+"'><a href='"+attach+"' target='_blank'>"+filename+"</a><span style='padding-top: 2px;font-weight: 600;vertical-align: middle;color: red;padding-left: 3px;'><i class='layui-icon' onclick='del_attchment("+i+")'>&#x1006;</i></span></p>")
            }
        }
    }

    //删除文件
    function del_attchment(index){
        attachments.splice(index, 1);
        $("#attachment_list"+index).remove();
    }

    //上传文件到存储桶
    function uploadCOS(file_arr) {
        let backUrls = "";
        //上传图片到存储桶
        for (let i in file_arr){
            let fileName = file_arr[i].name
            cos.putObject({
                Bucket: Bucket, /* 必须 */
                Region: Region,     /* 存储桶所在地域，必须字段 */
                Key:  folderName + "/" + fileName,/*文件夹+文件名称 必须 */
                Body: file_arr[i], // 上传文件对象
                onProgress: function(progressData) {
                    console.log(JSON.stringify(progressData));
                    let backUrl = "https://" + Bucket + ".cos."+ Region + ".myqcloud.com/" + folderName + "/" + fileName;
                    if(backUrls == ""){
                        backUrls = backUrl;
                    }else{
                        backUrls += "," + backUrl;
                    }
                    return backUrls;
                }
            }, function(err, data) {
                console.log(err || data);
            });
        }
        return backUrls;
    }
</script>

</html>
